var previewTimeout;
var myID = 0;
var tabComponent;
var pageID;


function setup(){
	$('#controlArea').css({
		'margin-top': '75px',
		'height': $('#UserResultArea').height(),
		'width': '329px'
	});
	
	//$('#controlArea').removeClass('ui-widget ui-widget-content ui-corner-all');
	$('#controlArea').css({ 'background': 'none' });
	tabComponent = $('#controlArea').tabs();
	
	$('#controlArea').bind('tabsshow', function(){
		window.location.hash = $('#controlArea').tabs().tabs('option', 'selected');
		pageID = $('#controlArea').tabs().tabs('option', 'selected');
		
		switch(pageID){
		
			case 0:
				searchBooks();
			break;
			
			case 1:
				searchPhotos();
			break;
			
			case 2:
				searchAlbums();
			break;
		
		
		}
	});
	
	// Select the current tab
	//try{
		tabComponent.tabs( "select" , parseInt(window.location.hash.substring(1, 2)) );
	//} catch (e){
	
	//}
		switch(parseInt(window.location.hash.substring(1, 2))){
		
			case 0:
				searchBooks();
			break;
			
			case 1:
				searchPhotos();
			break;
			
			case 2:
				searchAlbums();
			break;
		
			default:
				searchBooks();
			break;
		
		}

	
	$('#PBMyResourcesLink').children('div').css({ 'background-color': '#b8b8b8', 'background-image': 'none' });
	
	
	$('#filterOptions').buttonset();
	
	$('#photoFilters').buttonset();
	$('#albumFilters').buttonset();

	$('#filterOptions').bind('change', function(){
		searchBooks();
	});
	
	$('#search_box').keyup(function(e) {
		if(e.keyCode == 13) {
			searchBooks();
		}
	});	

	$('#photoFilters').bind('change', function(){
		searchPhotos();
	});

	$('#photo_search').keyup(function(e) {
		if(e.keyCode == 13) {
			searchPhotos();
		}
	});	


	$('#albumFilters').bind('change', function(){
		searchAlbums();
	});

	$('#album_search').keyup(function(e) {
		if(e.keyCode == 13) {
			searchAlbums();
		}
	});	
	
	$('#PBUploadPhoto').bind('click', function(){
		uploadDialog();
	});
	
	$('#PBCreateAlbum').bind('click', function(){
		getFragment("newImageset", function(data){
			jQuery.facebox(data);
			
			$.each(PicBoard.managedGroups, function(i, v){
				$('select#groupID').append( $("<option>", { 'val': parseInt(v[0]), 'text': v[1] }) );
			});			
			
			
			$('#saveImageset').bind('click', function(){
				$.post(PicBoard.baseURL + 'rsrc.php?req=createImageSet',$('#uploadForm').serialize(), function(data){
					if(data.statusCode == 200){
						searchAlbums();
						jQuery.facebox.close();
					} else {
						alert(data.message);
					}
				}, 'json');				
			});
		});	
	});
	
	$('#PBCreateBook').bind('click', function(){
		createBook();
	});
}

function createBook(){
	getFragment("createbook", function(data){
		jQuery.facebox(data);

		$.each(PicBoard.managedGroups, function(i, v){
			$('select#groupSaveLocation').append( $("<option>", { 'val': parseInt(v[0]), 'text': v[1] }) );
		});
		
		
		$('#PBCreateBookRequest').bind('click', function(){
			if($('input[name=saveLocation]:checked').val() == "local"){
				groupID = "";
			} else {
				groupID = parseInt($('select#groupSaveLocation').val());
			}
			
			book = { 'group_gID': groupID, 'name': $('#bookName').val() , 'description': $('#bookDescription').val() , 'visibility': 'bookOpen', 'type': 'personal' };
			
			if(book.bookName != ""){
				// Send the request.
				$.ajax({
					type: "POST",
					url: PicBoard.baseURL + "rsrc.php?req=createBook",
					data: book,
					dataType: 'json',
					success: function(data){
						
						if(data.statusCode == 200){
							window.location = "book?id=" + data.payload.bookID;
						}
					}				
				});
			} else {
				alert("Please set a name for this book before saving it.");
			}
		});
		
	});
}

function searchBooks(){
	$.ajax({
		url: PicBoard.baseURL + 'rsrc.php?req=searchBooks',
		dataType:'json',
		data: $('form#searchForm').serialize(),
		success: function(data){
			if(data.statusCode == 200){
				myID = data.uID;
				renderBookList(data.payload);
			} else {
				alert(data.message);
			}
		},
		'type': 'post'
	});	
}

function searchPhotos(){
	$.ajax({
		url: PicBoard.baseURL + 'rsrc.php?req=searchImages',
		dataType:'json',
		data: $('form#photoSearch').serialize(),
		success: function(data){
			if(data.statusCode == 200){
				myID = data.uID;
				renderImageList(data.payload);
			} else {
				alert(data.message);
			}
		},
		'type': 'post'
	});	
}

function searchAlbums(){
		$.ajax({
		url: PicBoard.baseURL + 'rsrc.php?req=searchImagesets',
		dataType:'json',
		data: $('form#albumSearch').serialize(),
		success: function(data){
			if(data.statusCode == 200){
				myID = data.uID;
				renderAlbumList(data.payload);
			} else {
				alert(data.message);
			}
		},
		'type': 'post'
	});	
}

function uploadDialog(){
	$.ajax({url: PicBoard.baseURL + 'rsrc.php?req=getUploadDialog', 
		success: function(data){
			jQuery.facebox(data);
			
			// IE sucks
			if($.browser.msie != true) $('button').button();
			
			// Redirect back here
			window.location.hash = pageID;
			$('input[name=redirectTo]').val(window.location);
			
			$('input[type=file][name=image]').change(function(){
				fileSplit = $('input[type=file]').val().match(/([^\\]+)\.[\w]{2,4}$/);
				$('input[name=fileName]').val(fileSplit[1]);
			});
			
			$('#uploadFileButton').bind('click', function(){
				// Get the filename
				filetype = $('input[type=file]').val().match(/\.(\w{2,4})$/);
				
				if($('input[type=file]').val() == ""){
					PicBoard.getTranslations(['lang_226_invalidFiletype'], function(data){
						alert(data.payload.lang_226_invalidFiletype);
					});					
				} else {
					filetype = filetype[1].toLowerCase();

					if(filetype == "png" || filetype == "jpg" || filetype == "jpeg" || filetype == "gif" || filetype == "wmf" || filetype == "svg"){
					
						// Before we submit the file for upload, check that the filename the user has chosen has not already been taken.
						$.post(PicBoard.baseURL + "rsrc.php?req=checkImageName", { isID: $('select#fileSaveLocations').val(), name: $('input[name=fileName]').val() }, 
							function(data){
								if(data.statusCode == 200){
									$("#uploadForm").submit();
								} else {
									alert(data.message);
								}
							}, 'json'
						);
						
					} else {
						PicBoard.getTranslations(['lang_226_invalidFiletype'], function(data){
							alert(data.payload.lang_226_invalidFiletype);
						});
					}
				}
			});
		}
	});
}

function renderBookList(data){
	table = $('<table>', { 'style': 'border:1px solid black; width: 90%; background:white' }).attr('align', 'center').append('<thead>');
	
	$(table).children('thead')
		.append($('<tr>').append(
				$('<th>', { text: 'Book' }),	
				$('<th>', { text: 'in Library' }),
				$('<th>', { text: 'Author' }),
				$('<th>', { text: 'Manage' }),
				$('<th>', { text: 'Book Editor' })
			));
	$(table).append('<tbody>');

	for(c in data){
		
		
		if(data[c].editable == "true"){
			manageLink = $('<a>', { href: "managebook?id=" + data[c].bID }).append($('<img>', { src: PicBoard.baseURL + 'images/gear.png', 'border': '0' }) );
		} else {
			manageLink = "";
		}
		
		$(table).children('tbody').append($('<tr>').data('chartData', {'identifier': parseInt(data[c].bID)  } ).append(
			$('<td>', { text: data[c].name }),			
			$('<td>', { text: data[c].library }),
			$('<td>', { text: data[c].ownerName }),
			$('<td>', { html: manageLink }),
			$('<td>', { html:
				$('<a>', { href: PicBoard.baseURL + "/" + PicBoard.language + "/" + 'bookeditor?id=' + data[c].bID }).append($('<img>', { src: PicBoard.baseURL + 'images/folder-open-slide.png', 'border':'0' }) )
			})
			)
		);
	}

	$('#UserResultArea').html(table);
}

function renderImageList(data){
	table = $('<table>', { 'style': 'border:1px solid black; width: 90%; background:white' }).attr('align', 'center').append('<thead>');
	
	$(table).children('thead')
		.append($('<tr>').append(
				$('<th>', { text: 'Photo' }),	
				$('<th>', { text: 'Album' }),
				$('<th>', { text: 'in Library' }),
				$('<th>', { text: 'in Community' }),
				$('<th>', { text: 'Author' }),
				$('<th>', { text: 'View' }),
				$('<th>', { text: 'Manage' })
			));
	$(table).append('<tbody>');

	for(c in data){
		
		
		if(data[c].editable == "true"){
			manageLink = $('<a>', { href: "managephotos?id=" + data[c].imgID }).append($('<img>', { src: PicBoard.baseURL + 'images/gear.png', 'border': '0' }) );
		} else {
			manageLink = "";
		}
		
		$(table).children('tbody').append($('<tr>').data('chartData', {'identifier': parseInt(data[c].imgID), 'thumbnail': data[c].imageURL  } ).append(
			$('<td>', { text: data[c].name }),			
			$('<td>', { text: data[c].album }),
			$('<td>', { text: data[c].library }),
			$('<td>', { text: data[c].community }),
			$('<td>', { text: data[c].ownerName }),
			$('<td>', { html: 
					$('<a>', { href: "#", 'class': 'viewLink' }).append($('<img>', { src: PicBoard.baseURL + 'images/folder-search-result.png', 'border': '0' }))
			}),
			$('<td>', { html: manageLink })
			)
		);
	}

	$('#UserResultArea').html(table);
	
	// Preview pane
	$('#UserResultArea').find('a.viewLink img').bind('mouseover', function(e){
		chartData = $(this).parent().parent().parent().data('chartData');
		
		if(chartData.thumbnail != null && $('#floatPreview').length == 0){
			floatDiv = $('<div>', { id: 'floatPreview', style: 'position:absolute; left:' + parseInt(e.pageX + 5) + 'px; top:' + parseInt(e.pageY + 5) + 'px; width:300px; height:300px' }).append($('<img>', { src: chartData.thumbnail }));
			$('body').append(floatDiv);
			
			clearTimeout(previewTimeout);
			
			if($('#floatPreview').children('img').height() > $('#floatPreview').children('img').width()){
				$('#floatPreview').children('img').css({ 'height':'300px', 'width':'auto' });
			} else {
				$('#floatPreview').children('img').css({ 'width':'300px', 'height':'auto' });
			}
		}
	});
	
	$('#UserResultArea').find('a.viewLink img').bind('mouseout', function(){
		//console.log('mouseout triggered');
		if($('#floatPreview').length > 0) {
			//console.log('no floatpreview detected');
			previewTimeout = setTimeout(function(){ $('#floatPreview').remove(); }, 500);
		}
	});
}

function renderAlbumList(data){
	table = $('<table>', { 'style': 'border:1px solid black; width: 90%; background:white;' }).attr('align', 'center').append('<thead>');
	
	$(table).children('thead')
		.append($('<tr>').append(
				$('<th>', { text: 'Album' }),
				$('<th>', { text: 'in Library' }),
				$('<th>', { text: 'in Community' }),
				$('<th>', { text: 'Author' }),
				$('<th>', { text: 'Manage' })
			));
	$(table).append('<tbody>');

	for(c in data){
		
		
		if(data[c].editable == "true"){
			manageLink = $('<a>', { href: "managealbum?id=" + data[c].isID }).append($('<img>', { src: PicBoard.baseURL + 'images/gear.png', 'border': '0' }) );
		} else {
			manageLink = "";
		}
		
		$(table).children('tbody').append($('<tr>').data('chartData', {'identifier': parseInt(data[c].isID), 'thumbnail': data[c].imageURL  } ).append(		
			$('<td>', { text: data[c].album }),
			$('<td>', { text: data[c].library }),
			$('<td>', { text: data[c].community }),
			$('<td>', { text: data[c].ownerName }),
			$('<td>', { html: manageLink })
			)
		);
	}

	$('#UserResultArea').html(table);
}


PicBoard.addLoadEvent( "setup()" );